package com.rework.joss.bsgrid.base;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSON;
import com.rework.joss.bsgrid.GridUtils;
/**
 * 
 * @ClassName. BaseController
 * @Description. TODO
 * @author zhangyang
 * @date 2016年3月24日 下午4:54:06
 * @version V1.0
 */
public class BaseController {

	
    public static final String ENCODE = "utf-8";
	
	protected void sendMessage(HttpServletResponse response, String str) throws Exception{
		response.setContentType("text/html; charset=" + ENCODE);
		PrintWriter writer = response.getWriter();
		writer.println(str);
		writer.close();
		response.flushBuffer();
	}
	/**
	 * 将某个对象转换成json格式并发送到客户端
	 * @param response
	 * @param obj
	 * @throws Exception
	 */
	protected void sendJsonMessage(HttpServletResponse response,Object obj) throws Exception{
		response.setContentType("text/html; charset=" + ENCODE);
		PrintWriter writer = response.getWriter();
		writer.println(JSON.toJSON(obj));
		writer.close();
		response.flushBuffer();
	}
	
	/**
	 * 当前页码
	 * @param request
	 * @return
	 */
	protected int getPageNum(HttpServletRequest request) {
		return GridUtils.getPageNum(request);
	}
	
	
	/**
	 * 每页显示记录数
	 * @param request
	 * @return
	 */
	protected int getInternal(HttpServletRequest request) {
		return GridUtils.getInternal(request);
	}
	
	/**
	 * 当前排序字段
	 * @param request
	 * @return
	 */
	protected String getSortName(HttpServletRequest request){
		return GridUtils.getSortName(request);
	}
	
	/**
	 * 当前排序类型
	 * @param request
	 * @return
	 */
	protected String getSortOrder(HttpServletRequest request){
		return GridUtils.getSortOrder(request);
	}
	
	/**
	 * 每条记录起始位置
	* @param records
	* @param page
	* @param limit
	* @exception.
	 */
	protected int getRecordStart(int records, int page, int limit) {
		return GridUtils.getRecordStart(records, page, limit);
	}
	
	protected void processJsonData4Grid(
			HttpServletRequest request, HttpServletResponse response, int limit, int page, int records, List rows) throws Exception {
		processJsonData4Grid(request,response, limit, page, records, rows, null);
	}
	
	private void processJsonData4Grid(
			HttpServletRequest request, HttpServletResponse response, int limit, int page, int records, List rows, Map userData) throws Exception {
		if(userData == null){
			userData = new HashMap();
		}
		sendMessage(response, GridUtils.constructJsonData4Grid(limit, page, records, rows, userData));
	}



}
